

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import model.FilesystemObject;
import model.FilesystemTreeModel;

/**
 * Node object for use in {@link FilesystemTreeModel}. Useful for custom toString() representation
 * of the {@link File} object, which will be used when displayed in a {@link JTree}. Also, allows
 * for testable getters/setters for the workshop.
 * 
 * @author Chris Moghbel (cmoghbel@ucsd.edu)
 */
public class FilesystemItem implements FilesystemObject {

  public File _file;
  public List<FilesystemObject> _children;
  public int _numChildren = 0;
  
  /**
   * Create a new FilesystemNode.
   * 
   * @param path the path to the file or directory
   */
  public FilesystemItem (String path) {
    _file = new File (path);
    populateChildren();
  }
  
  /**
   * Create a new FilesystemNode.
   * 
   * @param file the {@link File} representation of the file or directory
   */
  public FilesystemItem (File file) {
    _file = file;
    populateChildren();
  }
  
  /**
   * @param index the index to retreive from
   * @return the child at the given index
   */
  public FilesystemObject getChild (int index) {
    if (!isDirectory()) {
      return null;
    }
    Thread.sleep(1);
    return _children.get(index);
  }
  
  /**
   * {@inheritDoc}
   */
      @Override
      public String toString () {
                    return _file.getName();
}

  /**
   * Populates the nodes list of children.
   */
  private void populateChildren () {
    only directories have children
    if (_file.isDirectory()) {
      _children = new ArrayList<FilesystemObject>();
      for (File child : _file.listFiles()) {
        if (!child.isHidden()) {
          _children.add(new FilesystemNode(child));
        }
      }
      _numChildren = _children.size();
    }
  }
  
}
